<template>
  <el-dialog :close-on-click-modal="false" :title="`${mode === 'add' ? '新增' : '修改'}拖轮费率`" width="500px" v-model="visible" @confirm="confirm"
    @cancel="visible = false" @close="closeDialog">
    <div class="formData">
      <el-form :model="formData" ref="ruleForm" label-width="100px" :rules="rules">
        <el-form-item label="船长-起" prop="lengthStart">
          <el-input v-model="formData.lengthStart" placeholder="请填写船长-起(米)" />
        </el-form-item>
        <el-form-item label="船长-止" prop="lengthEnd">
          <el-input v-model="formData.lengthEnd" placeholder="请填写船长-止(米)" />
        </el-form-item>
        <el-form-item label="贸别" prop="tradeType">
          <el-radio-group v-model="formData.tradeType">
            <el-radio v-for="(item,i) in selects.tradeType" :key="i" :value="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="船舶类型" prop="shipKindCode">
          <Select placeholder="请选择船舶类型" :dataConfig="{ params: { type: 'DICT',dictType:'SHIP_KIND' } }" v-model:value="formData.shipKindCode" v-model:label="formData.shipKindName"/>
		  <!-- <el-select v-model:value="formData.shipKindCode" v-model:label="formData.shipKindName" placeholder="请选择船舶类型">
		  	<el-option v-for="item in selects.shipKindCode" :key="item.value" :label="item.label"
		  		:value="item.value" />
		  </el-select> -->
		</el-form-item>
        <el-form-item label="费率" prop="rate">
          <el-input v-model="formData.rate" placeholder="请填写费率" />
        </el-form-item>
      </el-form>
    </div>
	<template #footer>
	      <div class="dialog-footer">
	        <el-button @click="closeDialog">取消</el-button>
	        <el-button type="primary" @click="confirm">
	          确认
	        </el-button>
	      </div>
	    </template>
  </el-dialog>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		defineEmits,
		defineExpose,
		nextTick
	} from "vue";
	import { ElMessage, ElMessageBox,ElNotification } from "element-plus";
import Select from '@/components/Select/index.vue'
import api from '@/api/basicData/rate/index'
const emit = defineEmits(['callback'])

const selects = ref({
		shipKindCode: [{
				label: '类型1',
				value: 0
			},
			{
				label: '类型2',
				value: 1
			},
			{
				label: '类型3',
				value: 2
			}
		],
		tradeType: [
		  { label:"内贸",value:'N' },
		  { label:"外贸",value:'W' },
		]
	})

const visible = ref(false)
const mode = ref('add')
const row = ref({})
const formData = ref({
      lengthStart: '',
      lengthEnd: '',
      tradeType: 'N',
      shipKindCode: '',
      shipKindName: '',
	  rate:''
    })
  const ruleForm = ref({})
  
  // 验证大小
  const getLengthStart = (rule, value = rule.cellValue, callback) => {
  	if (formData.value.lengthEnd == 0) {
  		if (!callback) return
  		callback()
  	}
  	if (value > parseInt(formData.value.lengthEnd)) {
  		return new Error('船长-起数字不能大于船长-止数字')
  	}
  	if (!callback) return
  	callback()
  }
  const getLengthEnd = (rule, value = rule.cellValue, callback) => {
  	if (value < parseInt(formData.value.lengthStart)) {
  		return new Error('船长-止数字不能小于船长-起数字')
  	}
  	if (!callback) return
  	callback()
  }
  const validateAmount = (rule, value, callback) => {  
	  if (!value) {
		  return callback()
		}
      // 使用正则表达式校验小数点后是否只有两位  
      if (!/^-?\d+(\.\d{1,2})?$/.test(value)) {  
        callback(new Error('请输入数字'));  
      } else {  
        // 注意：这里可能还需要进一步处理，确保末尾不是".00"之类的，但为简化示例，暂不处理  
        callback();  
      }  
    }
  const rules = ref({
	lengthStart: [
		{ required: true, message: '不能为空', trigger: 'blur' },
		{ validator: getLengthStart, trigger: 'blur' },
		{ validator: validateAmount, trigger: 'blur' }
	],
	lengthEnd: [
		{ required: true, message: '不能为空', trigger: 'blur' },
		{ validator: getLengthEnd, trigger: 'blur' },
		{ validator: validateAmount, trigger: 'blur' }
	],
	rate: [
		{ required: true, message: '不能为空', trigger: 'blur' },
		{ validator: validateAmount, trigger: 'blur' }
	],
	shipKindCode: [
		{ required: true, message: '不能为空', trigger: 'blur' }
	]
  })
// 展示
const show = params => {
  visible.value = true
  mode.value = params?.mode || 'add'
  if (mode.value === 'edit') {
    row.value = params.row
    editInit()
  }
}
// 编辑
const editInit = async () => {
  const { data } = await api.getDetailById({id:row.value.id})
  formData.value = { ...data }
}
// 确认
const confirm = () => {
  ruleForm.value.validate(valid => {
    if (valid) {
		let request
		if (mode.value === 'add') {
		  request = api.save
		  delete formData.value.id
		} else {
		  request = api.save
		}
		request(formData.value).then(res => {
		  if (res.code == '200') {
		    ElMessage.success('保存成功')
		    visible.value = false
		    emit('callback')
		  } else {
		    ElMessage.error(res.msg)
		  }
		})
    } else {
      ElMessage.warning('请完善表单信息！')
    }
  })
}

// 重置
const closeDialog = () => {
  nextTick(() => {
    visible.value = false
    ruleForm.value.resetFields()
  })
}
defineExpose({
  show
})
</script>
